package com.zenithsun.news.newsinfo.controller;

import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.*;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.syzg.base.login.model.LoginObject;
import com.syzg.common.controller.BaseController;
import com.syzg.common.exception.BaseException;
import com.syzg.common.model.WebInfo;
import com.syzg.common.model.WebObj;
import com.syzg.common.util.MethodUtil;
import com.syzg.common.util.PKCreator;
import com.syzg.common.util.SearchMap;
import com.syzg.common.util.SystemUtil;
import com.syzg.core.page.PageResult;
import com.zenithsun.common.bean.ModelType;
import com.zenithsun.common.bean.OutMessage;
import com.zenithsun.common.bean.OutMessageState;
import com.zenithsun.common.image.StorageRule;
import com.zenithsun.common.review.model.Review;
import com.zenithsun.common.review.model.ReviewState;
import com.zenithsun.common.review.service.ReviewService;
import com.zenithsun.common.security.csrf.CSRFTokenManager;
import com.zenithsun.common.security.sql.SqlInjectionManager;
import com.zenithsun.common.security.xss.XSSFilterManager;
import com.zenithsun.common.util.FileUtil;
import com.zenithsun.news.newscolumns.model.NewsColumns;
import com.zenithsun.news.newsinfo.model.Newsdetailinfo;
import com.zenithsun.news.newsinfo.model.Newsinfo;
import com.zenithsun.news.newsinfo.service.NewsinfoService;
import com.zenithsun.news.solr.model.NewsInfo;
import com.zenithsun.news.solr.util.SolrHelper;
import com.zenithsun.news.specialnews.model.Specialnews;

@Controller
@RequestMapping("/path/newsinfo")
public class NewsinfoController extends BaseController {

	static Logger log = LoggerFactory.getLogger(NewsinfoController.class);

	@Resource
	private NewsinfoService newsinfoService;
		
	@Resource
	private ReviewService reviewService;
	
	@Autowired
	private  HttpServletRequest request;
	
	@RequestMapping("/listNewsinfo")
	public ModelAndView listNewsinfo(WebObj webObj) throws Exception {
		ModelAndView mv = new ModelAndView("/zenithsun/news/newsinfo/listNewsinfo.jsp");
		//主题
		SearchMap searchMap = SearchMap.forClass(NewsColumns.class);
		searchMap.eq("a.parentId", "0");
		@SuppressWarnings("unchecked")
		List<NewsColumns> lstNewsColumns = newsinfoService.findObjects(searchMap);
		mv.addObject("newsColumnsList", lstNewsColumns);
		return mv;
	}
	
	/**
	 * 新闻信息查询 后台新闻编辑中的查询
	 * @param newsinfo 新闻信息
	 * @param pageNo 当前页
	 * @param limit  页行数
	 * @return json
	 * @throws Exception
	 */
	
	@RequestMapping(value="/listNewsinfoForJson", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String listNewsinfoForJson(Newsinfo newsinfo,int pageNo,int limit) throws Exception {
		OutMessage outMessage = new OutMessage();
		PageResult pageResult = newsinfoService.queryNewsinfoSolr(pageNo, limit, newsinfo);
		outMessage.setContent(pageResult);
		outMessage.setState(OutMessageState.Success);
		String result= JSON.toJSONString(outMessage);
		return result;
	}

	/**
	 * 新闻信息查询 首页查询语句高亮显示
	 * @param newsinfo 新闻信息
	 * @param pageNo 当前页
	 * @param limit  页行数
	 * @return json
	 * @throws Exception
	 */
	
	@RequestMapping(value="/listNewsinfoForJsonTwo", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String listNewsinfoForJsonTwo(Newsinfo newsinfo,int pageNo,int limit) throws Exception {
		//解码
		String keyWord = URLDecoder.decode(URLDecoder.decode(newsinfo.getTitle(), "UTF-8"), "UTF-8");
		newsinfo.setTitle(keyWord);
		OutMessage outMessage = new OutMessage();
		PageResult pageResult = newsinfoService.queryNewsinfoSolrTwo(pageNo, limit, newsinfo);
		outMessage.setContent(pageResult);
		outMessage.setState(OutMessageState.Success);
		String result= JSON.toJSONString(outMessage);
		System.out.println(result);
		return result;
	}
	@SuppressWarnings("unchecked")
	@RequestMapping("/initNewsinfo")
	public ModelAndView initNewsinfo(String type) throws Exception {
		ModelAndView mv = null;
		Newsinfo newsinfo = new Newsinfo();
		try {
			if (type.equals("pic")) {
				mv = new ModelAndView("/zenithsun/news/newsinfo/addPicNewsinfo.jsp");
			} else {
				mv = new ModelAndView("/zenithsun/news/newsinfo/addWordNewsinfo.jsp");
			}
			//初始化规则，获取临时目录，将图片存入到临时目录中，在保存时才转入到数据库中存储
			StorageRule sr=new StorageRule(request);
			sr.setTempStore(true);
			newsinfo.setPicTempPath(sr.GetNewsImageStorePath());
			LoginObject loginObj = SystemUtil.getLoginObject();
			newsinfo.setEditor(loginObj.getPersonName());
			//将新闻内容存入mv中，可以在前端直接访问
			mv.addObject("newsinfo", newsinfo);
			SearchMap searchMap = SearchMap.forClass(NewsColumns.class);
			searchMap.eq("a.parentId", "0");
			List<NewsColumns> lstNewsColumns = newsinfoService.findObjects(searchMap);
			mv.addObject("newsColumnsList", lstNewsColumns);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return mv;
	}

	/**
	 * 保存新闻
	 * @param newsinfo
	 * @param type
	 * @param isReview 是否要提交审核
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/addNewsinfo")
	public @ResponseBody String addNewsinfo(Newsinfo newsinfo, String type,boolean isReview) throws Exception {
		WebObj webObj = new WebObj();
		try {
			boolean flag=this.newsinfoService.addNewsInfo(newsinfo, type,isReview, request);
			if(flag==true){
				setControllerStatus(webObj, WebInfo.STATUS_SUCCESS);
			} else{
				setControllerStatus(webObj, WebInfo.STATUS_FAILURE);
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error(BaseException.addExceptionLog(e));
			setControllerStatus(webObj, WebInfo.STATUS_FAILURE);
			webObj.getWebInfo().getErrorList().add("添加失败");
		}
		return JSON.toJSONString(webObj);
	}

	@RequestMapping("/viewNewsinfo2")
	public ModelAndView viewNewsinfo2(String newsId) throws Exception {
		ModelAndView mv=null;
		try {
			Newsinfo newsinfoVO = newsinfoService.findNewsinfoById(newsId);
			if ("pic".equals(newsinfoVO.getType())) {
				mv=new ModelAndView("/zenithsun/news/newsinfo/viewPicNewsinfo.jsp");
			} else {
				mv=new ModelAndView("/zenithsun/news/newsinfo/viewWordNewsinfo.jsp");
			}
			mv.addObject("newsinfo", newsinfoVO);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return mv;
	}
	
	/**
	 * 查看新闻封面
	 * @param newsinfo
	 * @param mv
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/initNewsCover")
	public ModelAndView initNewsCover(String id,String coverPath) throws Exception {
		try {
			ModelAndView mv=new ModelAndView("/zenithsun/plugins/Jcrop/newsCover.jsp");
			Newsinfo newsinfoVO = new Newsinfo();
			newsinfoVO.setId(id);
			newsinfoVO.setCoverPath(coverPath);
			mv.addObject("newsinfo", newsinfoVO);
			return mv;
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return null;
	}

	/**
	 * 剪切封面<br/>
	 * 以JSON的方式输出。<br/>
	 * wanglei@enersun.com.cn
	 * @createDate 2016-7-11 15:51:57
	 * @param newId （新闻ID）
	 * @param width
	 * @param height
	 * @param px_1
	 * @param py_1
	 * @param px_2
	 * @param py_2
	 * @return @ResponseBody String (数据格式请参考{@link OutMessage})
	 * @throws Exception
	 */
	@RequestMapping(value = "/cutCover", produces = "application/json;charset=UTF-8")
	public @ResponseBody String cutCover(String newId,int width,int height,int px_1,int py_1,int px_2,int py_2) throws Exception {
		OutMessage outMessage =null;
		try {
			outMessage= this.newsinfoService.cutCover(newId,width,height,px_1,py_1,px_2,py_2,request);
		} catch (Exception e) {
			outMessage = new OutMessage();
			log.error(BaseException.addExceptionLog(e));
			outMessage.setState(OutMessageState.Error);
			outMessage.setContent("操作失败");
		}
		return JSON.toJSONString(outMessage);
	}
	
	@RequestMapping("/viewNewsinfo")
	public ModelAndView viewNewsinfo(Newsinfo newsinfo, ModelAndView mv) throws Exception {
		try {
			Newsinfo newsinfoVO = newsinfoService.findNewsinfoById(newsinfo.getId());
			if ("pic".equals(newsinfoVO.getType())) {
				mv.setViewName("/zenithsun/news/newsinfo/viewPicNewsinfo.jsp");
			} else {
				mv.setViewName("/zenithsun/news/newsinfo/viewWordNewsinfo.jsp");
			}
			mv.addObject("newsinfo", newsinfoVO);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return mv;
	}

	@SuppressWarnings("unchecked")
	@RequestMapping("/editNewsinfo")
	public ModelAndView editNewsinfo(String id) throws Exception {
		SqlInjectionManager.validateSqlParam(id);
		ModelAndView mv = null;
		Newsinfo newsinfo = newsinfoService.findNewsinfoById(id);
		try {
			if (newsinfo.getType().equals("pic")) {
				mv = new ModelAndView("/zenithsun/news/newsinfo/editPicNewsinfo.jsp");
			} else {
				mv = new ModelAndView("/zenithsun/news/newsinfo/editWordNewsinfo.jsp");
				newsinfo.setContent(newsinfo.getContent().replaceAll("\"","&quot;"));
			}
			mv.addObject("newsinfo", newsinfo);
			WebObj webObj = new WebObj();
			mv.addObject("webObj", webObj);
			Review review=this.reviewService.getReview(newsinfo.getId(), ModelType.News.toString());
			boolean needReview=true;
			if(review!=null){
				if(ReviewState.ReviewSuccess.toShort()==review.getState()||ReviewState.WaitReview.toShort()==review.getState()){
					needReview=false;
				}
			}
			mv.addObject("needReview", needReview);
			mv.addObject("review", review);
			SearchMap searchMap = SearchMap.forClass(NewsColumns.class);
			searchMap.eq("a.parentId", "0");
			List<NewsColumns> lstNewsColumns = newsinfoService.findObjects(searchMap);
			mv.addObject("newsColumnsList", lstNewsColumns);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return mv;
	}

	/**
	 * 上传新闻图片为封面<br/>
	 * 该方法存在性能问题，每上传一张保存一条数据到后台，会造成频繁读取数据库<br/>
	 * wanglei@enersun.com.cn
	 * @createDate 2016-7-11 22:46:31
	 * @param request （请求对象）
	 * @param newsinfoId  （新闻ID）
	 * @return @ResponseBody String (failure为失败，success为成功)
	 * @throws Exception
	 */
	@RequestMapping(value = "/uploadCover", produces = "text/html;charset=UTF-8")
	public @ResponseBody String uploadCover(String newId,HttpServletRequest request) {
		OutMessage outMessage=null;
		try{
			outMessage=this.newsinfoService.uploadCover(newId, request);
		} catch (Exception e) {
			outMessage.setState(OutMessageState.Fail);
		}
		String json=JSON.toJSONString(outMessage,SerializerFeature.WriteNullStringAsEmpty);
		return json;
	}
	
	@RequestMapping("/modNewsinfo")
	public @ResponseBody String modNewsinfo(boolean isReview,String id, Newsinfo newsinfoVO) throws Exception {
		WebObj webObj = new WebObj();
		try {
			boolean flag=this.newsinfoService.modifyNewsInfo(isReview, id, newsinfoVO, request);
			if(flag){
				setControllerStatus(webObj, WebInfo.STATUS_SUCCESS);
			}else{
				setControllerStatus(webObj, WebInfo.STATUS_FAILURE);
			}
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
			setControllerStatus(webObj, WebInfo.STATUS_FAILURE);
			webObj.getWebInfo().getErrorList().add("操作失败");
		}
		return JSON.toJSONString(webObj);
	}

	@RequestMapping("/delNewsinfo")
	public ModelAndView delNewsinfo(String id, WebObj webObj) throws Exception {
		
		try {
			if(id!=null){
				String[] ids = id.split(",");
				String[] idsStr = new String[ids.length];
				int i = 0;
				for (String idVO : ids) {
					idsStr[i++] = new String(idVO);
				}
				newsinfoService.delNewsinfo(ids);
				SolrHelper.getInstance().delete(ids);
			}
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return listNewsinfo(webObj);
	}
	
	@RequestMapping(value = "/delNewsdetail", produces = "application/json;charset=UTF-8")
	public @ResponseBody String delNewsdetail(String selectedDetails, WebObj webObj) throws Exception {
		try {
			if(selectedDetails!=null){
				String[] ids = selectedDetails.split(",");
				String[] idsStr = new String[ids.length];
				int i = 0;
				for (String idVO : ids) {
					idsStr[i++] = new String(idVO);
				}
				//newsinfoService.delete(idsStr, Newsdetailinfo.class);
				newsinfoService.delNewsinfoDetail(idsStr,request);
				setControllerStatus(webObj, WebInfo.STATUS_SUCCESS);
			}
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
			setControllerStatus(webObj, WebInfo.STATUS_FAILURE);
		}
		return JSON.toJSONString(webObj);
	}

	@RequestMapping("/initPicUpload")
	public ModelAndView initPicUpload(String newsinfoId) {
		ModelAndView mv = new ModelAndView("/zenithsun/news/newsinfo/picUpload.jsp");
		try {
			Newsinfo newsinfo = newsinfoService.findNewsinfoById(newsinfoId);
			if (newsinfo == null) {
				newsinfo = new Newsinfo();
				newsinfo.setId(newsinfoId);
			}
			mv.addObject("newsinfo", newsinfo);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return mv;
	}
	
	/**
	 * 上传新闻图片<br/>
	 * 该方法存在性能问题，每上传一张保存一条数据到后台，会造成频繁读取数据库<br/>
	 * wanglei@enersun.com.cn
	 * @createDate 2016-7-6 09:32:51
	 * @param request （请求对象）
	 * @param newsinfoId  （新闻ID）
	 * @return @ResponseBody String (failure为失败，success为成功)
	 * @throws Exception
	 */
	@Deprecated
	@RequestMapping(value = "/newsPicUpload", produces = "application/json;charset=UTF-8")
	public @ResponseBody String picUpload(HttpServletRequest request, String newsinfoId,String picTempPath) {
		try{
			 String json = JSON.toJSONString(this.newsinfoService.uploadImageToPicNews(request, newsinfoId, picTempPath));
			 System.out.println(json);
			 return json;
		}catch(Exception e){
			OutMessage outMessage=new OutMessage();
			outMessage.setState(OutMessageState.Fail);
			outMessage.setContent("操作失败");
			return JSON.toJSONString(outMessage);
		}
	}

	@RequestMapping("/listImage")
	public ModelAndView listImage(String newsinfoId, String picTempPath) throws Exception {
		ModelAndView mv = null;
		if ("4View".equals(picTempPath)) {
			mv = new ModelAndView("/zenithsun/news/newsinfo/listImage4View.jsp");
		} else {
			mv = new ModelAndView("/zenithsun/news/newsinfo/listImage.jsp");
		}
		mv.addObject("lstNewsdetailinfo", this.newsinfoService.listImage(newsinfoId, picTempPath, request));
		mv.addObject("newsinfoId",newsinfoId);
		return mv;
	}

	/**
	 * 手机端，分栏展示数据加载<br/>
	 * 根据栏目信息进行向下翻页操作，以JSON的方式输出。<br/>
	 * 数据加载的时候<br/>
	 * wanglei@enersun.com.cn
	 * @createDate 2016-7-1 15:21:37
	 * @param ncId （新闻栏目ID）
	 * @param pageNo  （加载的页数）
	 * @return @ResponseBody String (数据格式请参考{@link OutMessage})
	 * @throws Exception
	 */
	@RequestMapping(value = "/listnewsjson", produces = "application/json;charset=UTF-8")
	public @ResponseBody
	String listnewsjson(String ncId, int pageNo) throws Exception {
		OutMessage outMessage = new OutMessage();
		try {
			Newsinfo news = new Newsinfo();
			news.setNewsColumns(new NewsColumns(ncId));
			// 每页查询的条数
			int pageSize = 5;
			// 通过新闻的栏目ID查询数据，每页查询pageSize条，pageNo为前端滑动后自增长+1
			PageResult pageResult = newsinfoService.queryNewsinfoPublished(pageNo,pageSize, news);
			// 查询的分页数据存入到统一输出对象的内容属性中
			outMessage.setContent(pageResult);
			outMessage.setState(OutMessageState.Success);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
			outMessage.setState(OutMessageState.Error);
			outMessage.setContent("操作失败");
		}
		return JSON.toJSONString(outMessage,SerializerFeature.WriteNullStringAsEmpty);
	}

	/**
	 * 手机端，分栏展示<br/>
	 * 根据新闻ID，判定是进入到图片新闻页面里面还是进入到文字新闻页面<br/>
	 * wanglei@enersun.com.cn
	 * @createDate 2016-7-1 15:21:16
	 * @param id  (新闻栏目ID)
	 * @return ModelAndView
	 * @throws Exception
	 */
	@RequestMapping("/initnewsCol_phone")
	public ModelAndView initnewsCol4Phone(String id) throws Exception {
		ModelAndView mv = new ModelAndView("/zenithsun/news/mobile/listnewsCol_phone.jsp");
		try {
			mv.addObject("newscolumnId", id);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return mv;
	}
	
	@RequestMapping("/initNewsByColumn_IOS")
	public ModelAndView initNewsByColumnToIOS(String id) throws Exception {
		ModelAndView mv = new ModelAndView("/zenithsun/news/mobile/listNewsByColumn_IOS.jsp");
		try {
			mv.addObject("newscolumnId", id);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return mv;
	}

	/**
	 * 手机端，分栏展示<br/>
	 * 根据新闻ID，判定是进入到图片新闻页面里面还是进入到文字新闻页面<br/>
	 * wanglei@enersun.com.cn
	 * @createDate 2016-7-1 15:21:16
	 * @param id  (新闻栏目ID)
	 * @return ModelAndView
	 * @throws Exception
	 */
	@RequestMapping("/initMobileIndex")
	public ModelAndView initMobileIndex(String id) throws Exception {
		ModelAndView mv = new ModelAndView("/zenithsun/news/mobile/index_phone.jsp");
		try {
			mv.addObject("newscolumnId", id);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return mv;
	}
	
	@RequestMapping("/initIosIndex")
	public ModelAndView initIosIndex(String id) throws Exception {
		ModelAndView mv = new ModelAndView("/zenithsun/news/mobile/ios.jsp");
		try {
			mv.addObject("newscolumnId", id);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return mv;
	}
	
	/**
	 * 手机端，新闻浏览<br/>
	 * 根据新闻ID，判定是进入到图片新闻页面里面还是进入到文字新闻页面<br/>
	 * wanglei@enersun.com.cn
	 * @createDate 2016-7-1 15:13:59
	 * @param id  (新闻ID)
	 * @return ModelAndView
	 * @throws Exception
	 */
	@RequestMapping("/viewnewsphone")
	public ModelAndView viewnewsphone(String id) throws Exception {
		// 默认进入到图片新闻详情中
		ModelAndView mv = new ModelAndView("/zenithsun/news/mobile/viewnewsPic_phone.jsp");
		try {
			// 通过新闻详情ID获取新闻内容
			Newsinfo newsVO = newsinfoService.findNewsinfoById(id);
			// 根据新闻详情里面的类型判定进入的页面
			// pic为图片新闻，text为文字新闻
			if ("pic".equals(newsVO.getType())) {
				mv.setViewName("/zenithsun/news/mobile/viewnewsPic_phone.jsp");
			} else {
				mv.setViewName("/zenithsun/news/mobile/viewnewsText_phone.jsp");
			}
			mv.addObject("news", newsVO);
			StorageRule sr=new StorageRule(request);
			sr.setTempStore(false);
			//获取新闻图片存储规则
			mv.addObject("newsImagePath", sr.GetNewsImageShowPath());
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return mv;
	}
	
	/**
	 * 下一图集的ID
	 * @param currentId 当前ID
	 * @return
	 * @throws Exception
	 */
	
	@RequestMapping(value = "/getRandomNewsId", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String getRandomNewsId(String currentId) throws Exception {
		OutMessage outMessage = new OutMessage();
		try {
			//下一图集的随机ID		
			String randomId = newsinfoService.getRandomNewsinfo(currentId);
			outMessage.setContent(randomId);
			outMessage.setState(OutMessageState.Success);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
			outMessage.setState(OutMessageState.Error);
			outMessage.setContent("操作失败");
		}
		return JSON.toJSONString(outMessage);
	}
	

	/**
	 * 手机端，单条新闻数据加载<br/>
	 * 以JSON的方式输出。<br/>
	 * wanglei@enersun.com.cn
	 * @createDate 2016-7-4 10:31:31
	 * @param newId （新闻ID）
	 * @return @ResponseBody String (数据格式请参考{@link OutMessage})
	 * @throws Exception
	 */
	@RequestMapping(value = "/viewnewsjson", produces = "application/json;charset=UTF-8")
	public @ResponseBody String viewnewsjson(String newId) throws Exception {
		OutMessage outMessage = new OutMessage();
		try {
			// 通过新闻ID查询新闻信息
			Newsinfo news = newsinfoService.getFullNewsinfoById(newId);
			// 查询的分页数据存入到统一输出对象的内容属性中
			outMessage.setContent(news);
			outMessage.setState(OutMessageState.Success);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
			outMessage.setState(OutMessageState.Error);
			outMessage.setContent("操作失败");
		}
		return JSON.toJSONString(outMessage);
	}
	
	@RequestMapping("/viewNewsdetail")
	public ModelAndView viewNewsdetail(Newsdetailinfo newsdetailinfo,ModelAndView mv) throws Exception {
		mv.setViewName("/zenithsun/news/newsinfo/viewNewsdetail.jsp");
		try {
			Newsdetailinfo newsdetailinfoVO = (Newsdetailinfo)newsinfoService.findObjectById(newsdetailinfo.getId(),Newsdetailinfo.class);
			if(newsdetailinfoVO == null){
				newsdetailinfoVO = new Newsdetailinfo();
				newsdetailinfoVO.setId(newsdetailinfo.getId());
				newsdetailinfoVO.setPath(newsdetailinfo.getPath());
			} else {
				newsdetailinfoVO.setPath(StorageRule.newsSavePath + newsdetailinfoVO.getPath());
			}
			mv.addObject("newsdetailinfo",newsdetailinfoVO);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return mv;
	}
	
	@RequestMapping(value="/saveNewsdetail",produces="application/text;charset=UTF-8")
	public @ResponseBody String saveNewsdetail(String id,Newsdetailinfo newsdetailinfoVO) throws Exception {
		WebObj webObj = new WebObj();
		try {
			Newsdetailinfo newsdetailinfo =(Newsdetailinfo)newsinfoService.findObjectById(id,Newsdetailinfo.class);
			newsdetailinfo = (Newsdetailinfo) MethodUtil.copyProperties(newsdetailinfo, newsdetailinfoVO);
			newsinfoService.update(newsdetailinfo);
			webObj.setObj((Object)newsdetailinfo);
			setControllerStatus(webObj,WebInfo.STATUS_SUCCESS);
			org.json.JSONObject jsonObject = new org.json.JSONObject(webObj);
			
			jsonObject.put("shootingTimeFmt", new SimpleDateFormat("yyyy-MM-dd HH:mm").format(newsdetailinfo.getShootingTime()));
			return jsonObject.toString();
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
			setControllerStatus(webObj,WebInfo.STATUS_FAILURE);
			webObj.getWebInfo().getErrorList().add("操作失败");
		}
		return new org.json.JSONObject(webObj).toString();
	}
	
	@RequestMapping(value="/mobileLogin",produces="application/json;charset=UTF-8")
	@ResponseBody 
	public String mobileLogin(String userName,String password) throws Exception {
		OutMessage outMessage=null;
		try {
			outMessage=this.newsinfoService.mobileLogin(userName, password);
		} catch (Exception e) {
			outMessage.setState(OutMessageState.Fail);
			outMessage.setContent("操作失败");
		}
		return JSON.toJSONString(outMessage);
	}

	/**
	 * 打开新闻详情
	 * @param  newsId 新闻的id
	 * @return mv
	 * @throws Exception
	 * */
	@RequestMapping("/frontNewsInfo")
	public ModelAndView frontTextNewsInfo(String newsId) throws Exception {
		SqlInjectionManager.validateSqlParam(newsId);
		ModelAndView mv=null;
		try {
			Newsinfo newsinfoVO = newsinfoService.getFullNewsinfoById(newsId);
			if ("pic".equals(newsinfoVO.getType())) {
				mv=new ModelAndView("/zenithsun/news/pc/imgNewsInfo.jsp");
			} else {
				mv=new ModelAndView("/zenithsun/news/pc/wordNewsInfo.jsp");
			}
			mv.addObject("newsinfo", newsinfoVO);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return mv;
	}

	/**
	 * 获取大家都在看和往期回顾新闻
	 * @return 新闻列表
	 * @throws Exception
	 * */
	@RequestMapping(value="/hotNewsList", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String getHotNewsList(String id) throws Exception {
		OutMessage outMessage = new OutMessage();
		try {
			//获取最新发布的八条新闻
			Map<String, Object> mapResultMap = new HashMap<>();
			List<Newsinfo> lstNewsinfo = newsinfoService.getLatestPublishNews(8);
			mapResultMap.put("Newsinfos", lstNewsinfo);
			String randomIdString = newsinfoService.getRandomNewsinfo(id);
			mapResultMap.put("nexId", randomIdString);
			outMessage.setContent(mapResultMap);
			outMessage.setState(OutMessageState.Success);
		}
		 catch (Exception e) {
			 outMessage.setState(OutMessageState.Fail);
			 log.error(BaseException.addExceptionLog(e));
		 }
			String result= JSON.toJSONString(outMessage);
		return result;
	}
	
	@RequestMapping(value="/mobileAddNews",produces="application/json;charset=UTF-8")
	@ResponseBody 
	public String mobileAddNews(String json,HttpServletRequest request) throws Exception {
		OutMessage outMessage=new OutMessage();
		try {
			// 解析 JSON
			JSONObject news = JSON.parseObject(json);
			// 转换为 model
			Newsinfo ni = new Newsinfo();
			String pk = PKCreator.getPk();
			String newsColumnId = news.getString("newsColumnsId");
			// NewsColumns
			NewsColumns columns = new NewsColumns();
			columns.setId(newsColumnId);
			// PK
			ni.setId(pk);
			ni.setNewsColumns(columns);
			ni.setTitle(news.getString("title"));
			ni.setContent(news.getString("content"));
			ni.setCorrespondent(news.getString("correspondent"));
			ni.setCoverPath(news.getString("coverPath"));
			ni.setCreateTime(new Date());
			ni.setEditor(news.getString("editor"));
			ni.setIsCarousel(Short.parseShort(news.getString("isCarousel").equals("YES") ? "1" : "0"));
			ni.setIsStriking(Short.parseShort(news.getString("isStriking").equals("YES") ? "1" : "0"));//
			ni.setIsTop(Short.parseShort(news.getString("isTop").equals("YES") ? "1" : "0"));
			ni.setKeyword(news.getString("keyword"));
			ni.setPhotographer(news.getString("photographer"));
			ni.setNewsTypeId("通讯");
			newsinfoService.create(ni);
			// 获取 pictures
			JSONArray pictures = JSON.parseArray(news.getJSONArray("pictures").toString());
			List<Newsdetailinfo> list = new ArrayList<Newsdetailinfo>();
			Newsdetailinfo detail = null;
			for (int i = 0; i < pictures.size(); i++) {
				JSONObject o = pictures.getJSONObject(i);
				// 二进制转换图片
				detail = new Newsdetailinfo();
				detail.setPath(FileUtil.writeFile(o.getString("picData"),
						o.getString("type")));
				detail.setNewsinfo(ni);
				detail.setOrderNo(i * 10);
				detail.setShootingTime(new Date());
				detail.setId(PKCreator.getPk());
				list.add(detail);
			}
			newsinfoService.saveNewsdetailinfoBatch(list);
			// pictures.
			outMessage.setState(OutMessageState.Success);
			outMessage.setContent("记录已保存");

		} catch (Exception e) {
			// TODO: handle exception
			outMessage.setState(OutMessageState.Success);
			outMessage.setContent("操作失败");
		}
		
		return JSON.toJSONString(outMessage);
	}
	/**
	 * 手机端访问栏目
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/getNewsColumns",produces="application/json;charset=UTF-8")
	@ResponseBody 
	public String getNewsColumns() throws Exception {
		
		OutMessage msg = new OutMessage();
		try {
			SearchMap searchMap = SearchMap.forClass(NewsColumns.class);
			searchMap.eq("a.parentId", "0");
			searchMap.addOrder("orderNo", (short)1);
			@SuppressWarnings("unchecked")
			List<NewsColumns> lstNewsColumns = newsinfoService.findObjects(searchMap);
			msg.setContent(lstNewsColumns);
			msg.setState(OutMessageState.Success);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			msg.setContent(null);
			msg.setState(OutMessageState.Fail);
		}
		
		return JSON.toJSONString(msg);
	}
	
	/**
	 * 新闻首页
	 * @param mv 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/index")
	public ModelAndView index(ModelAndView mv,String columnId) throws Exception {
		SqlInjectionManager.validateSqlParam(columnId);
		columnId=XSSFilterManager.xssEncode(columnId);
		mv.setViewName("/zenithsun/news/pc/index.jsp");
		try {
			List<HashMap<String, Object>> result = newsinfoService.listNewsinfo_carousel(4);
			mv.addObject("carouselNews",result);
			List<HashMap<String, Object>> tops = newsinfoService.listNewsinfo_top(10);
			
			mv.addObject("topNews",tops);
			SearchMap searchMap = SearchMap.forClass(NewsColumns.class);
			searchMap.eq("a.parentId", "0");
			searchMap.addOrder("orderNo", (short)1);
			@SuppressWarnings("unchecked")
			List<NewsColumns> lstNewsColumns = newsinfoService.findObjects(searchMap);
			mv.addObject("newsColumns", lstNewsColumns);
			if(columnId == null || columnId.equals(""))columnId = "";//默认 首页
			List<HashMap<String, Object>> newsByColumn = newsinfoService.listNewsinfo_columns(10, columnId);
			mv.addObject("newsByColumn", newsByColumn);
			mv.addObject("columnId", columnId);
			
			List<HashMap<String, Object>> specialNews = newsinfoService.getSpecialNewsUpToDate(1);
			mv.addObject("specialNews", specialNews.get(0));
			
			//CSRF_TOKEN_FOR_FORM_PARAM_NAME
			mv.addObject("CSRF_TOKEN_FOR_FORM_PARAM_NAME",CSRFTokenManager.CSRF_TOKEN_FOR_FORM_PARAM_NAME);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return mv;
	}
	
	/**
	 * 首页轮播
	 * @param carouselNum 行数
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/news-carousel-json", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String newsCarouselJson(int carouselNum)
			throws Exception {
		OutMessage outMessage = new OutMessage();
		List<HashMap<String, Object>> result = newsinfoService.listNewsinfo_top(carouselNum);
		outMessage.setContent(result);
		outMessage.setState(OutMessageState.Success);
		return JSON.toJSONString(outMessage);
	}
	
	/**
	 * 置顶新闻
	 * @param topNum 行数
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/news-top-json", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String newstopJson(int topNum)
			throws Exception {
		OutMessage outMessage = new OutMessage();
		// searchReview.setI
		List<HashMap<String, Object>> result = newsinfoService.listNewsinfo_top(topNum);
		outMessage.setContent(result);
		outMessage.setState(OutMessageState.Success);
		return JSON.toJSONString(outMessage);
	}
	
	/**
	 * 按主题查询新闻
	 * @param rows 行数
	 * @param columnId 主题ID
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/columns-news-json", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String newsByColumnsToJson(int rows,String columnId)
			throws Exception {
		OutMessage outMessage = new OutMessage();
		List<HashMap<String, Object>> result = newsinfoService.listNewsinfo_columns(rows, columnId);
		outMessage.setContent(result);
		outMessage.setState(OutMessageState.Success);
		return JSON.toJSONString(outMessage);
	}
	
	/**
	 * 最新新闻(新闻点击排行榜)
	 * @param rows 行数
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/news-upUpdate-json", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String newsByUpUpdateToJson(int rows)
			throws Exception {
		OutMessage outMessage = new OutMessage();
		List<HashMap<String, Object>> result = newsinfoService.listNewsinfo_upToDate(rows);
		outMessage.setContent(result);
		outMessage.setState(OutMessageState.Success);
		return JSON.toJSONString(outMessage);
	}
	

	/**
	 * 打开搜索页
	 * @param value 查询内容
	 * @return mv
	 * @throws Exception
	 * */
	@SuppressWarnings("unchecked")
	@RequestMapping("/search")
	public ModelAndView search(String value,HttpServletRequest request) throws Exception {
		/***XSS*******/
		value = URLDecoder.decode(value, "UTF-8");
		value = XSSFilterManager.xssEncode2(value);
		/***HTML form without CSRF protection*******/
		//if(StringUtil.isNotBlank(value)){CSRFTokenManager.validateForm(request);}
		ModelAndView mv=null;
		try {
			mv = new ModelAndView("/zenithsun/news/pc/search.jsp");
			//查询全部栏目
			SearchMap searchMap = SearchMap.forClass(NewsColumns.class);
			searchMap.eq("a.parentId", "0");
			searchMap.addOrder("orderNo", (short)1);
			List<NewsColumns> lstNewsColumns = newsinfoService.findObjects(searchMap);
			mv.addObject("newsColumns", lstNewsColumns);
			//判断有没有查询内容
			if(StringUtils.isNotBlank(value)){
				mv.addObject("searchValue", value);
			}else{
				mv.addObject("searchValue", "");
			}
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return mv;
	}

	/**
	 * 打开手机端的搜索页
	 * @param value 查询内容
	 * @return mv
	 * @throws Exception
	 * */
	@SuppressWarnings("unchecked")
	@RequestMapping("/searchMoblie")
	public ModelAndView searchMoblie(String value) throws Exception {
		ModelAndView mv=null;
		try {
			mv = new ModelAndView("/zenithsun/news/mobile/search_phone.jsp");
			//查询全部栏目
			SearchMap searchMap = SearchMap.forClass(NewsColumns.class);
			searchMap.eq("a.parentId", "0");
			searchMap.addOrder("orderNo", (short)1);
			List<NewsColumns> lstNewsColumns = newsinfoService.findObjects(searchMap);
			mv.addObject("newsColumns", lstNewsColumns);
			//判断有没有查询内容
			if(StringUtils.isNotBlank(value)){
				mv.addObject("searchValue", new String(value.getBytes("iso-8859-1"), "utf-8"));
			}
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return mv;
	}

	/**
	 * 打开专题新闻
	 * @return mv
	 * @throws Exception
	 * */
	@RequestMapping("/specialNews")
	public ModelAndView specialNews() throws Exception {
		ModelAndView mv=null;
		try {
			mv = new ModelAndView("/zenithsun/news/pc/specialNews.jsp");
			List<Specialnews> lstSpecialNews = newsinfoService.getSpecialNews();
			mv.addObject("specialNews", lstSpecialNews);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return mv;
	}
	
	/**
	 * 打开栏目
	 * @param columnid 栏目id
	 * @return mv
	 * @throws Exception
	 * */
	@SuppressWarnings("unchecked")
	@RequestMapping("/channel")
	public ModelAndView channel(String columnid) throws Exception {
		/**XSS 攻击**/
		columnid = XSSFilterManager.xssEncode2(columnid);
		ModelAndView mv=null;
		try {
			mv = new ModelAndView("/zenithsun/news/pc/channel.jsp");
			//查询全部栏目
			SearchMap searchMap = SearchMap.forClass(NewsColumns.class);
			searchMap.eq("a.parentId", "0");
			searchMap.addOrder("orderNo", (short)1);
			List<NewsColumns> lstNewsColumns = newsinfoService.findObjects(searchMap);
			mv.addObject("newsColumns", lstNewsColumns);
			//显示的栏目id
			if(StringUtils.isBlank(columnid) && lstNewsColumns.size() > 0){
				columnid = lstNewsColumns.get(0).getId();
			}
			mv.addObject("columnid", columnid);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return mv;
	}


	/**
	 * 根据栏目获取新闻（带分页）
	 * @return 新闻列表
	 * @throws Exception
	 * */
	@RequestMapping(value="/getNewsByColumn", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String getNewsByColumn(int pageNo,int limit,String columnid) throws Exception {
		/**validate SQL 盲注**/
		SqlInjectionManager.validateSqlParam(columnid);
		OutMessage outMessage = new OutMessage();
		try {
			Map<String, Object> resultMap = new HashMap<>();
			//根据栏目获取发布的新闻数量
			int count = newsinfoService.getPublishNewsCountByColumnid(columnid);
			int totalPage = (count + limit -1) / limit; //计算总页数
			resultMap.put("totalCount", count);
			resultMap.put("totalPageCount", totalPage);
			resultMap.put("currentPageNo", pageNo);
			//获取分页的新闻
			List<Newsinfo> lstNewsinfo = newsinfoService.getPublishNewsByColumnid(pageNo, limit, columnid);
			resultMap.put("items", lstNewsinfo);
			
			outMessage.setContent(resultMap);
			outMessage.setState(OutMessageState.Success);
		}
		 catch (Exception e) {
			 outMessage.setState(OutMessageState.Fail);
			 log.error(BaseException.addExceptionLog(e));
		 }
			String result= JSON.toJSONString(outMessage);
		return result;
	}
	
	/**
	 * 保存排序
	 * @param ids 已经排序的ID
	 * @param newsinfoId 新闻ID
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/saveSorts", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String saveSorts(String ids,String newsinfoId)
			throws Exception {
		OutMessage outMessage = new OutMessage();
		List<Newsdetailinfo> result;
		try {
			String[] idArray = ids.split(",");
			result = newsinfoService.listImage(newsinfoId);
			//List<Newsdetailinfo> resultSorts = new ArrayList<Newsdetailinfo>();
			Newsdetailinfo detail = null;
			Map<String, Newsdetailinfo> map = new HashMap<String, Newsdetailinfo>();
			//设置为key-value方式存储，便于获取
			for (int i = 0; i < result.size(); i++) {
				map.put(result.get(i).getId() , result.get(i));
			}
			for (int i = 0; i < idArray.length; i++) {
				if(idArray[i] != null && !"".equals(idArray[i])){
					//根据ID获取图片
					detail =  map.get(idArray[i]);
					//设置序号
					detail.setOrderNo(i);
					//存储到待保存容器中
					//resultSorts.add(detail);
					
					newsinfoService.update(detail);
				}
			}
			//newsinfoService.updateSortsNewsdetailinfoBatch(resultSorts);
			outMessage.setContent("记录已保存");
			outMessage.setState(OutMessageState.Success);
		} catch (Exception e) {
			// TODO 异常处理
			log.error(e.getMessage());
			outMessage.setContent("操作失败");
			outMessage.setState(OutMessageState.Fail);
		}
		return JSON.toJSONString(outMessage);
	}

	/**
	 * 更新数据库的浏览量
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/modCounter")
	public @ResponseBody String modCounter(String id) throws Exception {
		SqlInjectionManager.validateSqlParam(id);
		try {
			Newsinfo newsinfo=this.newsinfoService.findNewsinfoById(id);
			newsinfo.setPageViewCounter(newsinfo.getPageViewCounter()+1);
			newsinfoService.update(newsinfo);
			//
			SolrHelper.getInstance().insert(new NewsInfo(newsinfo));
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return null;
	}
}